----------------------------------------------------------------
-- Global Variables
----------------------------------------------------------------

----------------------------------------------------------------
-- AuctionListDataManager Functions
--
-- Allows for multiple AuctionList data to exist at the same time
--
----------------------------------------------------------------

AuctionListDataManager = 
{
	DEBUG_ON = false,
	DEBUG_LEVEL = 7,
	
	SortPricesPerCount = true,

    -- column names
    iconHeader          = GetStringFromTable( "AuctionHouseStrings",  StringTables.AuctionHouse.SEARCH_RESULTS_HEADER_ICON ),
    itemNameHeader      = GetStringFromTable( "AuctionHouseStrings",  StringTables.AuctionHouse.SEARCH_RESULTS_HEADER_ITEM_NAME ),
    rankHeader          = GetStringFromTable( "AuctionHouseStrings",  StringTables.AuctionHouse.SEARCH_RESULTS_HEADER_RANK ),
    durationHeader      = GetStringFromTable( "AuctionHouseStrings",  StringTables.AuctionHouse.SEARCH_RESULTS_HEADER_TIME_LEFT ),
    bidPriceHeader      = GetStringFromTable( "AuctionHouseStrings",  StringTables.AuctionHouse.SEARCH_RESULTS_HEADER_CURRENT_BID ),
    buyOutPriceHeader   = GetStringFromTable( "AuctionHouseStrings",  StringTables.AuctionHouse.SEARCH_RESULTS_HEADER_BUY_OUT ),
    bidderHeader        = GetStringFromTable( "AuctionHouseStrings",  StringTables.AuctionHouse.SEARCH_RESULTS_HEADER_HIGH_BIDDER ),
    sellerHeader        = GetStringFromTable( "AuctionHouseStrings",  StringTables.AuctionHouse.SEARCH_RESULTS_HEADER_SELLER ),

	BIDDER_SELLER_COLUMN_NUMBER = 5,
}

AuctionData = {}


----------------------------------------------------------------
-- Local Functions
----------------------------------------------------------------

local function SendDebug( text, level )
	level = level or 5
	
    if AuctionListDataManager.DEBUG_ON and level >= AuctionListDataManager.DEBUG_LEVEL then
        DEBUG( text )
    end
end


--------------------------------------------
-- local Comparator functions for columns --

-- sorts by rarity, and then stack count within rarity (higher stack counts first)
local function rarityComparator( a, b )  
    if a.itemData.rarity == b.itemData.rarity then
        return a.itemData.stackCount > b.itemData.stackCount  
    end
    
    return a.itemData.rarity > b.itemData.rarity  
end


local function defaultComparator( a, b )	return( a.originalIndex < b.originalIndex )		end

--local function nameComparator( a, b )   return( WStringsCompare( a.itemData.name, b.itemData.name ) == -1 )  end
--local function sellerComparator( a, b )   return( WStringsCompare( a.sellerName, b.sellerName ) == -1 )  end
--local function bidderComparator( a, b )   return( WStringsCompare( a.highBidderName, b.highBidderName ) == -1 )
local function nameComparator( a, b )		return( a.itemData.name < b.itemData.name )		end
local function sellerComparator( a, b )		return( a.sellerName < b.sellerName )			end
local function bidderComparator( a, b )		return( a.highBidderName < b.highBidderName )	end
local function rankComparator( a, b )		return a.itemData.level < b.itemData.level		end
local function durationComparator( a, b )	return a.timeLeft < b.timeLeft					end 

-- a money value of 0 should be sorted to the end.
local function moneyComparator( moneyA, moneyB ) 
	if moneyA == 0 then
		return false
	elseif moneyB == 0 then
		return true
	else
		return moneyA < moneyB
	end
end

local function pricePerCount( money, itemData ) 

    if( itemData.stackCount > 1 ) then
        return money / itemData.stackCount
    else
        return money
    end
end

local bidPriceComparator
local buyOutComparator

if AuctionListDataManager.SortPricesPerCount then

	bidPriceComparator = function( a, b )	return( moneyComparator( pricePerCount( a.currentBid, a.itemData ), pricePerCount( b.currentBid, b.itemData ) ) )	end
	buyOutComparator = function( a, b )		return( moneyComparator( pricePerCount( a.buyOutPrice, a.itemData ), pricePerCount( b.buyOutPrice, b.itemData ) ) ) end
else

	bidPriceComparator = function( a, b )	return moneyComparator( a.currentBid, b.currentBid	 )	end
	buyOutComparator = function( a, b )		return moneyComparator( a.buyOutPrice, b.buyOutPrice )	end
end


----------------------------------------------------------------
-- Local Functions
----------------------------------------------------------------

local ALDM = AuctionListDataManager 


-----------------------
-- Column Data Table --

ALDM.DefaultColumnData =
{
    [0] = { column = "",        text=L"",					   sortFunc=defaultComparator,  },
    { column = "Icon",          text=ALDM.iconHeader,          sortFunc=rarityComparator,   },
    { column = "Name",          text=ALDM.itemNameHeader,      sortFunc=nameComparator,     },
    { column = "Rank",          text=ALDM.rankHeader,          sortFunc=rankComparator,     },
    { column = "Duration",      text=ALDM.durationHeader,      sortFunc=durationComparator, },
    { column = "Seller",        text=ALDM.sellerHeader,        sortFunc=sellerComparator,   },
    { column = "BidPrice",      text=ALDM.bidPriceHeader,      sortFunc=bidPriceComparator, },
    { column = "BuyOutPrice",   text=ALDM.buyOutPriceHeader,   sortFunc=buyOutComparator,   },
}


ALDM.MyAuctionsColumnData =
{
    [0] = { column = "",        text=L"",					   sortFunc=defaultComparator,  },
    { column = "Icon",          text=ALDM.iconHeader,          sortFunc=rarityComparator,   },
    { column = "Name",          text=ALDM.itemNameHeader,      sortFunc=nameComparator,     },
    { column = "Rank",          text=ALDM.rankHeader,          sortFunc=rankComparator,     },
    { column = "Duration",      text=ALDM.durationHeader,      sortFunc=durationComparator, },
    { column = "Seller",        text=ALDM.bidderHeader,        sortFunc=bidderComparator,   },
    { column = "BidPrice",      text=ALDM.bidPriceHeader,      sortFunc=bidPriceComparator, },
    { column = "BuyOutPrice",   text=ALDM.buyOutPriceHeader,   sortFunc=buyOutComparator,   },
}


----------------------------------------------------------------
-- AuctionData Functions
----------------------------------------------------------------

function AuctionData.CreateData( tabNumber )

	local newData = 
		{
			-- DEBUG: remove before checkin
			tabNumber = tabNumber,
			-- END DEBUG:

			sortColumnNum = 0,               -- column number to sort by
			sortColumnName = "",              -- column name currently sorting by
			shouldSortIncresing = true,       -- DEFAULT_SORTING
		    
			searchResultsData = {},
			displayOrder = {},          -- used for switching between up and
			reverseDisplayOrder = {},   --   down sort directions
		    
			currentlySelectedRowName = "",      -- remember windowName when selecting a row
			currentlySelectedRow = 0,
			-- hopefully support Selecting Multiple rows in the 
			--currentlySelectedRows = {},
		    
			myBid = 0,
		} 
		
	-- headers are hardcoded to all use the same columns,
	--		but this could be more variable in the future
	if tabNumber == AuctionHouseWindow.TAB_BROWSE_ID then 
		newData.columnData = ALDM.DefaultColumnData 
	else
		newData.columnData = ALDM.MyAuctionsColumnData
	end
	return newData
end


----------------------------------------------------------------
-- AuctionListDataManager Functions
----------------------------------------------------------------

-- called directly by AuctionHouseWindow.Initialize()
function AuctionListDataManager.Initialize()
	SendDebug(L"AuctionListDataManager.Initialize", 7)

	-- Initialize the hardcoded tabs
    ALDM.tabs = 
    {
		{ data=AuctionData.CreateData(1),	autoRefresh=false,	queryData=nil	},
		{ data=AuctionData.CreateData(2),	autoRefresh=true,	queryData=ALDM.CreteMyBidsQuery()	},
		{ data=AuctionData.CreateData(3),	autoRefresh=true,	queryData=ALDM.CreteMyAuctionsQuery()	},
    }
    ALDM.currentTab = 1
    
    -- TODO: in the future it would be nice to allow player's to save their own tabs of favorite searches

end

function AuctionListDataManager.Clear()
	SendDebug(L"AuctionListDataManager.Clear", 7)

	-- TODO: this should probably clear more tab specific data once we figure out
	--		which data we want to keep on a per tab basis
	for i, tabData in ipairs(AuctionListDataManager.tabs) do
		tabData.data = AuctionData.CreateData(i)
    end
    
    -- clear any saved queryData
    AuctionListDataManager.tabs[AuctionHouseWindow.TAB_BROWSE_ID].data.queryData = nil
end

function AuctionListDataManager.SetCurrentTabNumber( tabNumber )
	SendDebug(L"AuctionListDataManager.SetCurrentTabNumber tabNumber="..tabNumber, 4)

	if tabNumber > 0 and tabNumber <= #AuctionListDataManager.tabs and
	   AuctionListDataManager.currentTab ~= tabNumber then
	   	
	   	-- TODO: show/hide different sections
	   	--AuctionHouseWindow.SetSectionShowing( sectionName, isMinimized )
	   	
	   	AuctionListDataManager.currentTab = tabNumber
		
		local tabData = AuctionListDataManager.tabs[AuctionListDataManager.currentTab]
		if tabData.autoRefresh then
			AuctionListDataManager.SendAuctionSearch( tabData.queryData )
			SendDebug(L"   AuctionListDataManager.SetCurrentTabNumber is sending default query to auto refresh tab Number="..AuctionListDataManager.currentTab, 7)
		end
		
		return true
	end
	
	return false
end

function AuctionListDataManager.GetCurrentTabNumber()

	return AuctionListDataManager.currentTab
end

function AuctionListDataManager.GetWindowData( listID )
	SendDebug(L"AuctionListDataManager.GetWindowData listID="..listID, 2)
	
    return AuctionListDataManager.tabs[ listID ].data
end

function AuctionListDataManager.GetCurrentWindowData()

    return AuctionListDataManager.GetWindowData( AuctionListDataManager.currentTab )
end

function AuctionListDataManager.IsMyAuctionsPaneShowing()

	return AuctionListDataManager.currentTab == AuctionHouseWindow.TAB_AUCTIONS_ID 
end

function AuctionListDataManager.IsMyBidsPaneShowing()

	return AuctionListDataManager.currentTab == AuctionHouseWindow.TAB_BIDS_ID 
end


function AuctionListDataManager.CreteMyBidsQuery()

	local queryData = AuctionListDataManager.CreteEmptyQuery()
    queryData.bidderName = GameData.Player.name
    return queryData
end

function AuctionListDataManager.CreteMyAuctionsQuery()

	local queryData = AuctionListDataManager.CreteEmptyQuery()
	queryData.sellerName = GameData.Player.name
    return queryData
end

function AuctionListDataManager.CreteEmptyQuery()

	return( {
			usableOnly = false,
			minPrice = 0,
			maxPrice = 0,
			minItemLevel = 0,
			maxItemLevel = 0,  
			minRarity = SystemData.ItemRarity.UTILITY,
			career = 0,
			restrictionType = GameData.Auction.RESTRICTION_NONE,
			minTradeSkillLevel = 0,
			maxTradeSkillLevel = 0,   
			
			itemTypes = {},
			itemEquipSlots = {},
			itemBonuses = {},

			itemName = L"",
			sellerName = L"",
			bidderName = L"",

			} )
end

function AuctionListDataManager.SendAuctionSearch( queryData )

    SendAuctionSearch( queryData.usableOnly,
                       queryData.minPrice,
                       queryData.maxPrice,
                       queryData.minItemLevel,
                       queryData.maxItemLevel,    
                       queryData.minRarity,
                       queryData.career,
                       queryData.restrictionType,
                       queryData.minTradeSkillLevel,
                       queryData.maxTradeSkillLevel, 
            
                       queryData.itemTypes,
                       queryData.itemEquipSlots,
                       queryData.itemBonuses,
                       
                       queryData.itemName,
                       queryData.sellerName,
                       queryData.bidderName
                     )
end
